﻿using UnityEngine;
using System.Collections;
using System.Collections.Concurrent;


public delegate void OnResponseMessageHandler(MessageResponse response);
public class ResponseMessageManager
{

    private readonly ReadSocketDataManager readSocketDataManager;
    private readonly RequestMessageManager requestMessageManager;
    public event OnResponseMessageHandler PushMessageHandler;
    //接收消息队列
    private readonly ConcurrentQueue<MessageResponse> responseMessageQueue = new ConcurrentQueue<MessageResponse>();
    public ResponseMessageManager(ReadSocketDataManager readSocketDataManager,RequestMessageManager requestMessageManager)
    {
        this.readSocketDataManager = readSocketDataManager;
        this.requestMessageManager = requestMessageManager;
        this.readSocketDataManager.ReadSocketDataEventHandler += OnReadMessage;
    }

    public void OnReadMessage(ByteBuf byteBuf)
    {
        if (!byteBuf.IsReadable()) {
            return;
        }
        byteBuf.MarkReaderIndex();
        byteBuf.ReadInt();
        int messageId = byteBuf.ReadInt();
        if(messageId > 1000) //与服务器约定，大于1000的消息号是业务消息
        {
            byteBuf.ResetReaderIndex();
            MessageResponse response = CodecFactory.DecodeMessage(byteBuf);
            this.responseMessageQueue.Enqueue(response);
        } else
        {
            byteBuf.ResetReaderIndex();
        }
    }
    public void Update()
    {
        FixReadResponse();
    }

    private void FixReadResponse()
    {
        MessageResponse response;
        bool flag = this.responseMessageQueue.TryDequeue(out response);
        if (flag && response != null)
        {
            MessageRequest nowRequest = requestMessageManager.GetCurrentMessageRequest();
            int responseSeqId = response.Header.SeqId;
            int nowSeqId = nowRequest.Header.SeqId;
            int messageType = response.Header.MessageType;
            if (messageType == 1 && nowSeqId == responseSeqId)
            {
                Debug.Log("收到服务器返回消息号:" + response.Header.MessageId);
                nowRequest.ResponseHandler(response);
                requestMessageManager.DeleteCurrentMessageRequest();
            }
            else if (messageType == 2)
            {
                //处理服务器推送
                if (PushMessageHandler != null)
                {
                    Debug.Log("收到服务器推送消息号:" + response.Header.MessageId);
                    PushMessageHandler(response);
                }

            }
            else if (messageType == 3)
            {
                //处理心跳
            }

        }

    }


}
